from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from .forms import UserLoginForm, AuthRegisterForm
from django.contrib.auth.decorators import permission_required
from .models import UserDetail
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json


def auth_register(request):
    context = dict()
    context['form'] = AuthRegisterForm()
    if request.method == "POST":
        print(request.POST)
        print(request.FILES)
        form = AuthRegisterForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data.get('username', None)
            password = form.cleaned_data.get('password', None)
            portrait = None if len(request.FILES) == 0 else request.FILES.get('portrait')
            if User.objects.filter(username=username).exists():
                context['error_message'] = 'username已注册'
            else:
                u = User.objects.create_user(username, password)
                if u and portrait is not None:
                    detail = UserDetail.objects.create(user=u, portrait=portrait)
                login(request, u)
                return HttpResponseRedirect(reverse("users:auth_info"))
        context['form'] = form
    return render(request, "auth/register.html", context)


def user_login(request):
    context = dict()
    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get("username", None)
            password = form.cleaned_data.get('password', None)
            # 验证用户名密码
            user = authenticate(request, username=username, password=password)

            if user is None:
                context['form'] = form
                context['error_message'] = '用户名或密码不正确'
            else:
                login(request, user)
                next_url = request.GET.get('next', None)
                if not next_url:
                    next_url = reverse("users:login_success")
                return HttpResponseRedirect(next_url)
    else:
        context['form'] = UserLoginForm()
    return render(request, "auth/base.html", context)


def user_login_success(request):
    context = dict()
    if request.user.is_anonymous:
        return HttpResponse("真的未登录呀")
    if request.user.is_authenticated:
        # context['user'] = request.user
        pass
    else:
        return HttpResponseRedirect(reverse("users:auth_login"))
    return render(request, "auth/login_success.html", context)


def auth_logout(request):
    if request.user.is_authenticated:
        logout(request)
    return HttpResponseRedirect(reverse("users:auth_login"))


@login_required(login_url="/users/auth_login/")
def auth_info(request):
    context = dict()
    return render(request, 'auth/auth_info.html', context)


@login_required
@permission_required("users.view_auth_detail", raise_exception=True)
def auth_detail(request):
    return render(request, 'auth/detail.html', dict())


@require_http_methods(['GET'])
def user_login_static(request):
    return render(request, "ajax/login.html")


@csrf_exempt
@require_http_methods(['POST'])
def ajax_user_login(request):
    if request.method == "POST":
        datas = dict(result=0)
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get("username", None)
            password = form.cleaned_data.get('password', None)
            # 验证用户名密码
            user = authenticate(request, username=username, password=password)

            if user is None:
                datas['error_message'] = '用户名或密码不正确'
            else:
                datas['result'] = 1
                login(request, user)
                next_url = request.GET.get('next', None)
                if not next_url:
                    next_url = reverse("users:login_success")
                datas['next_url'] = next_url
        else:
            datas['result'] = -1
            datas['error_message'] = '账号或密码有误。请检查后再次登录'
            datas['error_html'] = json.dumps(form.errors)
        return JsonResponse(datas)
